package com.yc.dynamic.config;

import lombok.extern.java.Log;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源配置
 */
@Log
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<DSName> dataSourceKey = new InheritableThreadLocal<DSName>() {
        @Override
        protected DSName initialValue() {
            return DSName.testDataSource;
        }
    };

    public static void setDataSource(DSName dataSource) {
        dataSourceKey.set(dataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        Object ds = dataSourceKey.get();
        if (ds != null) {
            System.out.println(ds);
            log.warning("current datasource " + ds.toString());
        } else {
            System.out.println(ds);
            log.warning("use default datasource");
        }
        return ds;
    }
}
